package com.imay.live.activity.user;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.imay.base.helper.NetworkHelper;
import com.imay.base.util.MD5Util;
import com.imay.live.activity.BaseUserActivity;
import com.imay.live.activity.MainActivity2;
import com.imay.live.activity.user.util.RegisterCodeTimer;
import com.imay.live.analytics.MobclickAgent;
import com.imay.live.cache.UserInfoCache;
import com.imay.live.fragment.user.UserBaseFragment;
import com.imay.live.helper.CallBack;
import com.imay.live.helper.DialogFragmentHelper;
import com.imay.live.helper.EventHelper;
import com.imay.live.helper.PreferenceHelper;
import com.imay.live.manager.AccountManager;
import com.imay.live.manager.EditTextManager;
import com.imay.live.model.UserInfoModel;
import com.imay.live.proto.ErrorResult;
import com.imay.live.proto.ResultCode;
import com.imay.live.proto.account.AccountCheckSmsResp;
import com.imay.live.proto.account.AccountResetPasswordResp;
import com.imay.live.proto.account.AccountSendSmsResp;
import com.imay.live.proto.helper.ProtoHttpFactory;
import com.imay.live.proto.helper.ProtoRequestHelper;
import com.imay.live.utils.ToastUtil;
import com.imay.live.R;
import com.imay.tbas_api.IMYScheduler;

import java.util.ArrayList;
import java.util.List;

import static com.imay.live.proto.ResultCode.CodeSuccess;

/**
 * 注册
 * Created by chan on 2017/3/28.
 */

public class ResigterActivity extends UserBaseActivity implements View.OnClickListener {

    private String checkSmsRequest;
    private String resetPsdRequest;
    private String sendSmsRequest;
    private String bindPhoneRequest;

    private static final int REQUEST_CODE = 200;

    private static RegisterCodeTimer mCodeTimer;

    public static String USER_STATUS = "user_key";
    public static final int STATUS_REGISTER = 0;
    public static final int STATUS_FORGOT_PASSWORD_AUTO_LOGIN = 1;
    public static final int STATUS_BIND_PHONE = 2;
    public static final int STATUS_MODIFY_PHONE = 3;
    public static final int STATUS_FORGOT_PASSWORD_NO_LOGIN = 4;

    private int status; // 0 注册，1 忘记密码
    private TextView mTime;
    private TextView mRegisterSure;
    private TextView mLocalView;
    private String local = "86";
    private EditText mPhone, mSms, mPsd;
    private Context mContext;

    private long mPhoneFinal;
    private long mSmsFinal;
    private String mSecret;
    private long mPhoneNumber;

    private EditTextManager manager;

    public static void startActivity(Activity activity, int key) {
        Intent intent = new Intent(activity, ResigterActivity.class);
        Bundle bundle = new Bundle();
        bundle.putInt(USER_STATUS, key);
        intent.putExtras(bundle);
        activity.startActivity(intent);
    }

    public static void startActivityForResult(Activity activity, int key, int requestCode) {
        Intent intent = new Intent(activity, ResigterActivity.class);
        Bundle bundle = new Bundle();
        bundle.putInt(USER_STATUS, key);
        intent.putExtras(bundle);
        activity.startActivityForResult(intent, requestCode);
    }

    public static void startForResult(Activity activity, int requestCode, int key) {
        Intent intent = new Intent(activity, ResigterActivity.class);
        Bundle bundle = new Bundle();
        bundle.putInt(USER_STATUS, key);
        intent.putExtras(bundle);
        activity.startActivityForResult(intent, requestCode);
    }

    @Override
    protected boolean isTranslucentStatus() {
        return false;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_register;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        mContext = this;
        manager = EditTextManager.getInstance();
        mRegisterSure = $(R.id.tv_register_sure);

        status = getIntent().getIntExtra(USER_STATUS, -1);
        if (status == STATUS_REGISTER) {
            setTitle(getString(R.string.str_register_title));
            mRegisterSure.setText(getString(R.string.str_register_next));
        } else if (status == STATUS_FORGOT_PASSWORD_AUTO_LOGIN || status == STATUS_FORGOT_PASSWORD_NO_LOGIN) {
            setTitle(getString(R.string.str_respsw_title));
            mRegisterSure.setText(getString(R.string.str_sure));
        } else if (status == STATUS_BIND_PHONE) {
            setTitle(getString(R.string.account_bind_phone_number));
            mRegisterSure.setText(getString(R.string.str_sure));
        } else if (status == STATUS_MODIFY_PHONE) {
            setTitle(getString(R.string.account_modity_phone_number));
            mRegisterSure.setText(getString(R.string.account_bind_phone_number));
        }

        mRegisterSure.setOnClickListener(this);

        mPhone = $(R.id.tv_register_phone);
        mSms = $(R.id.tv_register_sms);
        mPsd = $(R.id.tv_register_psd);

        mPsd.setTag("psd");
        manager.changeBgColor(mRegisterSure, R.drawable.shape_corner100_bc, R.drawable.shape_corner100_9e, mPhone, mSms, mPsd);

        mTime = $(R.id.tv_respsd_time);
        mTime.setClickable(true);
        mTime.setOnClickListener(this);

        mLocalView = $(R.id.tv_area_local);
        mLocalView.setOnClickListener(this);

        manager.setEditClear((ImageView) $(R.id.iv_phone_clear), mPhone, mSms, mPsd);
        manager.setEditClear((ImageView) $(R.id.iv_sms_clear), mSms);
        manager.setEditClear((ImageView) $(R.id.iv_psd_clear), mPsd);
        MobclickAgent.onEvent(this, "register_open");
    }

    /**
     * 倒计时Handler
     */
    Handler mCodeHandler = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what == RegisterCodeTimer.IN_RUNNING) {// 正在倒计时
                mTime.setText((String) msg.obj);
                mTime.setBackground(getResources().getDrawable(R.drawable.shape_corner5_white_70));
                mTime.setTextColor(getResources().getColor(R.color.text_20));
            } else if (msg.what == RegisterCodeTimer.END_RUNNING) {// 完成倒计时
                mTime.setText(getString(R.string.str_respsw_time_reset_text));
                mTime.setClickable(true);
                mTime.setBackground(getResources().getDrawable(R.drawable.shape_corner5_white_02));
                mTime.setTextColor(getResources().getColor(R.color.text_30));
            }
        }
    };

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_respsd_time:
                MobclickAgent.onEvent(this, "register_click_sendcode");
                if (!NetworkHelper.getInstance().hasConnection()) {
                    DialogFragmentHelper.closeLoadingDialog(getSupportFragmentManager());
                    ErrorResult.toastError(mContext, ResultCode.CodeNetErrorAction);
                    return;
                }

                CharSequence phoneStr = mPhone.getText();
                if (!TextUtils.isEmpty(phoneStr)) {
                    mCodeTimer = new RegisterCodeTimer(60000, 1000, mCodeHandler);
                    mCodeTimer.start();
                    mTime.setClickable(false);
                    sendSms(phoneStr.toString());
                }
                break;
            case R.id.tv_area_local:
                LocalActivity.startActivity(this, REQUEST_CODE);
                break;
            case R.id.tv_register_sure:
                MobclickAgent.onEvent(this, "register_click_next");
                if (!NetworkHelper.getInstance().hasConnection()) {
                    DialogFragmentHelper.closeLoadingDialog(getSupportFragmentManager());
                    ErrorResult.toastError(mContext, ResultCode.CodeNetErrorAction);
                    return;
                }

                phoneStr = mPhone.getText();
                long phone = 0;
                if (TextUtils.isEmpty(phoneStr)) {
                    return;
                }

                final CharSequence smsStr = mSms.getText();
                long sms = 0;
                if (TextUtils.isEmpty(smsStr)) {
                    return;
                }

                final CharSequence psdStr = mPsd.getText();
                long psd = 0;
                if (TextUtils.isEmpty(psdStr)) {
                    return;
                }

                phone = Long.parseLong(phoneStr.toString());
                mPhoneNumber = Long.parseLong(phoneStr.toString());
                sms = Long.parseLong(smsStr.toString());

                // 加密的密码
                mSecret = MD5Util.getMD5(phoneStr.toString() + psdStr.toString());

                DialogFragmentHelper.showLoadingDialog(getSupportFragmentManager(), mContext.getString(R.string.str_register_loading));
                if (status == STATUS_REGISTER) { // 注册
                    // 检测验证码
                    mPhoneFinal = phone;
                    mSmsFinal = sms;
                    checkSmsRequest = ProtoRequestHelper.task(ProtoHttpFactory.checkSms(Integer.parseInt(local), phone, smsStr.toString())).setTag(this.hashCode()).request(this);
                } else if (status == STATUS_FORGOT_PASSWORD_AUTO_LOGIN || status == STATUS_FORGOT_PASSWORD_NO_LOGIN) { // 重置密码
                    resetPsdRequest = ProtoRequestHelper.task(ProtoHttpFactory.resetPsd(Integer.parseInt(local), phone, smsStr.toString(), mSecret, null)).setTag(this.hashCode()).request(this);
                } else if (status == STATUS_BIND_PHONE || status == STATUS_MODIFY_PHONE) { // 绑定手机
                    bindPhoneRequest = ProtoRequestHelper.task(ProtoHttpFactory.bindPhone(Integer.parseInt(local), phone, smsStr.toString(), mSecret)).setTag(this.hashCode()).request(this);
                }
                break;
        }
    }

    @Override
    public void onRequestSuccess(String command, String data) {
        DialogFragmentHelper.closeLoadingDialog(getSupportFragmentManager());
        if (command.equals(sendSmsRequest)) { // 发送验证码
            AccountSendSmsResp resp = JSONObject.parseObject(data, AccountSendSmsResp.class);
            if (resp.result == CodeSuccess) { //成功
                mSms.requestFocus();
                ToastUtil.show(mContext, R.string.str_phone_send_success);
            } else { //该手机号已注册
                mCodeTimer.cancel();
                mTime.setText(R.string.str_respsw_time_text);
                mTime.setClickable(true);
                mTime.setBackground(getResources().getDrawable(R.drawable.shape_corner5_white_02));
                mTime.setTextColor(getResources().getColor(R.color.color_00));
                ErrorResult.toastError(mContext, resp.result);
            }
        } else if (command.equals(resetPsdRequest)) { // 重置密码
            AccountResetPasswordResp resp = JSON.parseObject(data, AccountResetPasswordResp.class);
            if (resp.result == CodeSuccess) {
                PreferenceHelper.getInstance().clearSec();
                if (status == STATUS_FORGOT_PASSWORD_AUTO_LOGIN) {
                    login();
                } else if (status == STATUS_FORGOT_PASSWORD_NO_LOGIN) {
                    AccountManager.getInstance().logout(null);
                    //UserActivity.startActivity(ResigterActivity.this);
                    IMYScheduler.getInstance().stopSocketService();
                    IMYScheduler.getInstance().startSocketService();
                    MainActivity2.startActivityForLogout(ResigterActivity.this, BaseUserActivity.OPEN_USER_FRAGMENT);
                }
            } else {
                ErrorResult.toastError(mContext, resp.result);
            }
        } else if (command.equals(checkSmsRequest)) {
            AccountCheckSmsResp resp = JSONObject.parseObject(data, AccountCheckSmsResp.class);
            if (resp.result == CodeSuccess) {
                InformationActivity.startActivityForResult(ResigterActivity.this, Integer.parseInt(local), mPhoneFinal, mSmsFinal, mSecret, UserBaseFragment.REQUEST_RESIGTER);
            } else {
                ErrorResult.toastError(mContext, resp.result);
            }
        } else if (command.equals(bindPhoneRequest)) {
            AccountCheckSmsResp resp = JSONObject.parseObject(data, AccountCheckSmsResp.class);
            if (resp.result == CodeSuccess) {
                UserInfoModel model = UserInfoCache.getUserInfo();
                model.setPhone(mPhoneNumber);
                UserInfoCache.saveUserInfo(model);
                PreferenceHelper.getInstance().savePhone(mPhoneNumber + "");
                EventHelper.postUpdateUserInfo();
                setResult(RESULT_OK);
                finish();
            } else {
                ErrorResult.toastError(mContext, resp.result);
            }
        }
    }

    private void login() {
        DialogFragmentHelper.showLoadingDialog(getSupportFragmentManager(), getString(R.string.str_login_forget));
        if (TextUtils.isEmpty(local)) {
            return;
        }
        final int localNum = Integer.parseInt(local);

        if (mPhoneNumber == 0) {
            return;
        }

        final String finalPhone = Long.toString(mPhoneNumber);

        AccountManager.getInstance().loginByPasswordHttp(localNum, mPhoneNumber, mSecret, new CallBack() {
            @Override
            public void onSuccess() {
                DialogFragmentHelper.closeLoadingDialog(getSupportFragmentManager());

                PreferenceHelper.getInstance().saveUserInf(localNum, finalPhone, mSecret);

                ToastUtil.showImg(mContext, getString(R.string.str_login_success), R.mipmap.jiaohutishidagou_3x, 200);
                // 登录时，传递分享回调参数
                /*if (first) {
                    SuggestActivity.startActivity(ResigterActivity.this);
                } else {*/
                //MainActivity2.startActivity(ResigterActivity.this, getIntent().getStringExtra(H5Helper.H5REDIRECTION_KEY));
                //}
                //ActivityHelper.getInstance().finishActivity(UserActivity.class);
                setResult(RESULT_OK);
                finish();
            }

            @Override
            public void onError(int code, String message) {
                DialogFragmentHelper.closeLoadingDialog(getSupportFragmentManager());
                ToastUtil.showImg(mContext, ErrorResult.getString(mContext, code), R.mipmap.jiaohutishidaxia_3x, 200);
            }
        });
    }

    @Override
    public void onRequestError(String command, int code, String message) {
        DialogFragmentHelper.closeLoadingDialog(getSupportFragmentManager());
        ErrorResult.toastError(mContext, code);
        if (command.equals(sendSmsRequest)) {
            mCodeTimer.cancel();
            mTime.setText(R.string.str_respsw_time_text);
            mTime.setClickable(true);
            mTime.setBackground(getResources().getDrawable(R.drawable.shape_corner5_white_02));
            mTime.setTextColor(getResources().getColor(R.color.color_00));
        }
    }

    /**
     * 发送验证码
     *
     * @param phone
     */
    private void sendSms(String phone) {
        // 发送验证码
        int sendType = 0;
        switch (status) {
            case STATUS_REGISTER:
            case STATUS_BIND_PHONE:
            case STATUS_MODIFY_PHONE:
                sendType = 1;
                break;
            case STATUS_FORGOT_PASSWORD_AUTO_LOGIN:
            case STATUS_FORGOT_PASSWORD_NO_LOGIN:
                sendType = 2;
                break;
        }
        sendSmsRequest = ProtoRequestHelper.task(ProtoHttpFactory.sendSms(Integer.parseInt(local), Long.parseLong(phone), sendType)).setTag(this.hashCode()).request(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mCodeTimer != null) {
            mCodeTimer.cancel();
        }
        if (mCodeHandler != null) {
            mCodeHandler.removeCallbacksAndMessages(null);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE) {
            if (resultCode == RESULT_OK) {
                local = data.getStringExtra("local_text");
                mLocalView.setText("+" + local);
            }
        } else if (requestCode == UserBaseFragment.REQUEST_RESIGTER) {
            if (resultCode == RESULT_OK) {
                setResult(RESULT_OK);
                finish();
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }
}
